package com.fruit.auth.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.CollectionUtils;

import com.fruit.auth.model.Privilege;
import com.fruit.auth.model.User;
/**
 * 检查用户是否具有某个url访问权限工具类
 * @author Administrator
 *
 */
public class PrivilegeUtil
{
	
	@SuppressWarnings("unchecked")
	public static boolean hasPrivilege(String actionName, HttpServletRequest req)
	{
		User u=(User) req.getSession().getAttribute("user");
		if(u==null)
			return false;
		else if(u.isAdmin())
			return true;
		else
		{
			if(actionName.contains("?"))
				actionName=actionName.substring(0,actionName.indexOf("?"));
			String accessUrl="/"+actionName+".action";
			Map<String,Privilege> allPrivileges=(Map<String, Privilege>) req.getServletContext().getAttribute("allPrivileges");
			if(CollectionUtils.isEmpty(allPrivileges))
				return false;
			Privilege privilege=allPrivileges.get(accessUrl);
			if(privilege!=null)
				return u.hasPrivilege(privilege);
			return false;
		}
	}
}
